package com.ihome.android.market2.asynctask;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;

import com.ihome.android.EAApp;
import com.ihome.android.academy.MainActivity;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.frag.UpdateAppFragment;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.DownloadDialog;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.util.AppMgr;
import com.ihome.android.util.PkgSizeObserver;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

public class GetUpdateAppTask extends AsyncTask<Bundle, Integer, Bundle> {
	private String			TAG				= GetUpdateAppTask.class.getSimpleName();
	private Context			mContext;
	private Fragment		fragment;
	private String			updateUrl		= "";
	private String			appMD5			= "";
	private String			appName			= "";

	private List<AppInfo>	mUpdateAppList	= new ArrayList<AppInfo>();

	public GetUpdateAppTask(Context mContext) {
		this.mContext = mContext;
	}

	public GetUpdateAppTask(Context mContext, Fragment fragment) {
		this.mContext = mContext;
		this.fragment = fragment;
	}

	@Override
	protected Bundle doInBackground(Bundle... params) {
		Bundle b = params[0];
		try {

			List<AppInfo> mAppList = AppMgr.getInstance().loadDataApps(mContext);

			if (mAppList != null) {
				//LogUtil.v(TAG, "mAppList.size = " + mAppList.size());
				for (AppInfo appinfo : mAppList) {
					AppMgr.queryPkgSize(mContext, appinfo, new PkgSizeObserver(appinfo));
				}

				JSONArray element = new JSONArray();
				String paramValue = "";
				for (int i = 0; i < mAppList.size(); i++) {
					JSONObject item = new JSONObject();
					item.put("pkgName", mAppList.get(i).getPkgName());
					item.put("version", mAppList.get(i).getVersion());
					element.put(item);
				}
				paramValue = URLEncoder.encode(element.toString(), "UTF-8");
				LogUtil.v(TAG, "Chekc APP Need Update -->" + paramValue);

				String isupdateApp = new HttpActions(mContext).appIsUpdate(paramValue);
				LogUtil.v(TAG, "gNeedUpdateAppList() --> result = \n" + isupdateApp);
				if (!TextUtils.isEmpty(isupdateApp)) {
					List<AppInfo> mListAppUTemp = JsonAnalytic.getInstance().anslyseUpdateAppResult(isupdateApp);

					//过滤不需要更新的App
					for (int j = 0, len = mListAppUTemp.size(); j < len; j++) {
						if (mListAppUTemp.get(j).isNeedUpdate()) {
							//民生强制升级
							if (ConfigUtil.MINSHENG_KEY.equals(mListAppUTemp.get(j).getPkgName())) {
								AppInfo appinfo = mListAppUTemp.get(j);
								String dlApp = new HttpActions(mContext).downApp(0, "" + appinfo.getAppId(), 0);
								LogUtil.v(TAG, "getAppUrl result-->" + dlApp);
								if (!TextUtils.isEmpty(dlApp)) {
									updateUrl = JsonAnalytic.getInstance().anslyseAppDLUrlResult(dlApp);
									appMD5 = JsonAnalytic.getInstance().anslyseAppDLMD5Result(dlApp);
									appName = appinfo.getAppName();
								}
							}
							else {
								mUpdateAppList.add(mListAppUTemp.get(j));
							}
						}
					}

					for (AppInfo updateInfo : mUpdateAppList) {
						for (AppInfo installedinfo : mAppList) {
							if (updateInfo.getPkgName().equals(installedinfo.getPkgName())) {
								updateInfo.setUid(installedinfo.getUid());
								updateInfo.setTotalsize(installedinfo.getTotalsize());
							}
						}
					}
				}
			}
			else {
				cancel(true);
			}

		} catch (Exception e) {
			String[] msg1 = { "", "", "" , "", "app.IsUpdate", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
			if (e instanceof ITVException) {
				b.putInt(HttpKeys.KEY_CODE, ((ITVException) e).getStatusCode());
				b.putString(HttpKeys.KEY_DESCRIPTION, ((ITVException) e).getMessage());
			}
			else {
				e.printStackTrace();
				LogUtil.e(TAG, e.toString());
			}

		}
		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);

		/** 请求出错处理 */
		if (result.containsKey(HttpKeys.KEY_CODE)) {
			if(ITVException.HTTP_GET_HTTP_URL_CONN_IO_EXCEPTION == result.getInt(HttpKeys.KEY_CODE)){
				DialogFactory.onBtnClickListener don = new onBtnClickListener() {

					public void btnRightClickListener(View v) {
						EAApp.getApp().exitApp(true);
					}

					public void btnNeutralClickListener(View v) {


					}

					public void btnLeftClickListener(View v) {
						// TODO Auto-generated method stub
						new GetUpdateAppTask(mContext).execute(new Bundle());

					}

					@Override
					public void btnCloseClickListener(View v) {

					}
				};

				new DialogFactory(mContext).showDialog2Btn(mContext.getString(R.string.attention_error), result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")","重试","取消",don);
			}else{
				if(ITVException.CODE_LOGINOUT_THREE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGINOUT_ONE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_SESSIONKEY == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGIN_ONE == result.getInt(HttpKeys.KEY_CODE)){
					new DialogFactory(mContext).showDialog("",result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")",mContext.getString(R.string.dialog_ok),new onBtnClickListener() {
						
						@Override
						public void btnRightClickListener(View v) {
							// TODO Auto-generated method stub
						}
						
						@Override
						public void btnNeutralClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void btnLeftClickListener(View v) {
							// TODO Auto-generated method stub
							EAApp.getApp().exitApp(true);
						}
						
						@Override
						public void btnCloseClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
					});
					return;
				}
				new DialogFactory(mContext).showDialog(result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")");
			}			

			return;
		}

		if (fragment != null && fragment instanceof UpdateAppFragment) {
			((UpdateAppFragment) fragment).getAppSuccess(mUpdateAppList, mUpdateAppList.size());
		}

		EAApp.getApp().mUpdateAppList = mUpdateAppList;
		if (mContext instanceof MainActivity) {
			if (!TextUtils.isEmpty(updateUrl) && !TextUtils.isEmpty(appName)) {
				LogUtil.v(TAG, "To DownloadDialog ....");
				LogUtil.v(TAG, "DownloadDialog yueshenghuo install-->" + appName + "\t appMD5 = " +appMD5);
				new DownloadDialog(mContext, appName, updateUrl, ConfigUtil.MINSHENG_KEY, appMD5).show();
			}
//			((MainActivity) mContext).checkNeedUpdateApp(mUpdateAppList.size());
		}
	}

}
